package encomendaFacil.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {

	private static final ConnectionFactory INSTANCE = new ConnectionFactory();
	
	private Connection conn;
	
	private static final String DRIVER = "org.postgresql.Driver";
	private static final String USER = "root";
	private static final String PASSWORD = "root";
	private static final String URL = "jdbc:postgresql://localhost:5432/encomendafacil_db";
	
	private ConnectionFactory() {
		try {
			Class.forName(DRIVER);
			conn = null;
		} catch (ClassNotFoundException e) {
			//usar log4j
			e.printStackTrace();
		} 
	}
	
	public static ConnectionFactory getInstance(){
		if (INSTANCE == null) {
			return new ConnectionFactory();
		}
		return new ConnectionFactory();
	}
	
	public Connection getConnection(){
		if (conn == null) {
			try {
				conn = DriverManager.getConnection(URL, USER, PASSWORD);
				return conn;
			} catch (SQLException e) {
				//usar log4j
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	public void closeConnection(){
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				//usar log4j
				e.printStackTrace();
			}
		}
	}
}
